<template>
  <div class="wap">
    <button class="button" type="primary" @click="onGetAuthorize">同意邀请成为店员
    </button>
    <div v-if="sjid==''">未获取到商家ID</div>
    <div v-if="sjid!==''">已获取商家ID:{{sjid}}</div>
    <div v-if="!autuCodeFLag">未获取到授权码..</div>
    <div v-if="autuCodeFLag">已获取用户授权码:{{authCode}}</div>
    <div v-if="zz">正在入库..</div>
    <div v-if="cg">入库成功!..</div>
    <div v-if="!cg&&zz">入库失败!..</div>
    <div v-if="userId!==''">已经获取到UserId:{{userId}}</div>
    <div v-if="error!==''">错误信息:{{error}}</div>
  </div>
</template>

<script>
  import store from '@/store/store'
  import {isEmpty} from 'lodash'

  export default {
    computed: {
      companyId () {
        return store.state.companyId
      }
    },
    data () {
      return {
        sjid: '',
        autuCodeFLag: false,
        zz: false,
        authCode: '',
        cg: false,
        error: '',
        userId: ''
      }
    },
    methods: {
      setAuthCode (res) {
        this.autuCodeFLag = true
        this.authCode = res.authCode
        store.commit('setAuthCodeNoId', res.authCode)
      },
      setUserInfo (res) {
        this.userInfoFlag = true
        store.commit('setUserInfo', res)
      },
      onGetAuthorize (res) {
        this.mpvue.getAuthCode({
          scopes: 'auth_user',
          fail: (res) => {
            this.mpvue.alert({content: '请允许获取授权码！'})
            this.onGetAuthorize()
            this.autuCodeFLag = false
          },
          success: (res) => {
            this.setAuthCode(res)
            this.saveData(res.authCode)
          }
        })
      },
      saveData (authCode) {
        this.zz = true
        let url = store.state.server + '/auth/SjInsert'
        this.cg = false
        this.mpvue.request({
          url: url,
          data: {
            authCode,
            sjid: this.sjid
          },
          fail: (res) => {
            this.cg = false
          },
          success: (res) => {
            this.cg = true
            this.error = res.data.error
            this.userId = res.data.userId
            if (!isEmpty(this.userId)) {
              this.mpvue.alert({
                content: '操作成功',
                buttonText: '我知道了',
                success: () => {
                  const url = '/pages/chose/index'
                  this.mpvue.navigateTo({url})
                }
              })
            }
          }
        })
      }
    },

    onLoad (options) {
      this.sjid = options.sjid
      store.commit('setCompanyId', options.sjid)
      // this.mpvue.alert({content: '启动参数：' + JSON.stringify(options)})
    },
    onUnload () {
    }
  }
</script>

<style scoped lang="scss">
  @import "../../common/common";

  .wap {
    padding: 30px 20px;

    div {
      margin: 10px 0;
      color: #1a6f95;
    }
  }

</style>
